#include <iostream>
#include <memory>

using std::cout;
using std::endl;
using std::shared_ptr;

class Child;//类的前向声明

class Parent
{
public:
    Parent()
    {
        cout << "Parent()" << endl;
    }

    ~Parent()
    {
        cout << "~Parent()" << endl;
    }

    shared_ptr<Child> parent;
};

class Child
{
public:
    Child()
    {
        cout << "Child()" << endl;
    }

    ~Child()
    {
        cout << "~Child()" << endl;
    }

    shared_ptr<Parent> child;
};

void test()
{
    shared_ptr<Parent> pParent(new Parent());
    shared_ptr<Child> pChild(new Child());
    cout << "pParent.use_count() = " << pParent.use_count() << endl;
    cout << "pchild.use_count() = " << pChild.use_count() << endl;

    cout << endl;
    pParent->parent = pChild;
    pChild->child = pParent;
    cout << "pParent.use_count() = " << pParent.use_count() << endl;
    cout << "pchild.use_count() = " << pChild.use_count() << endl;
    //此代码存在内存泄漏
}

int main(int argc, char **argv)
{
    test();
    return 0;
}

